package com.kingboy.kbg.devop.sonar;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingboy.kbg.devop.sonar.model.SonarComponentKeyVO;
import com.kingboy.kbg.devop.sonar.model.SonarSearchProjectVO;
import okhttp3.*;

import java.io.IOException;
import java.util.List;

/**
 * Create By 郭金宝 on 2018/6/28.<br>
 */
public class SonarTest {
    public static final String SONAR_HOST = "http://114.116.24.133:9000/sonar";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private final OkHttpClient client = new OkHttpClient();
    private static final String allProjectsPath = "/api/components/search_projects";


    /**
     * 获取某个项目扫描结果
     * @param url
     * @return
     * @throws IOException
     */
    public String getSonarResult(String url) throws IOException {
        Request okRequest = new Request.Builder().url(SONAR_HOST + url).build();
        Response response = client.newCall(okRequest).execute();
        if (!response.isSuccessful()) throw new IOException("Unexpected code "   + response);
        System.out.println(response.body().charStream());
        return response.body().string();
    }

    public String sendSonar(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(SONAR_HOST + url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String getProjectsKeys(String[] projectsIdName,List<SonarComponentKeyVO> componentsKeys){
        //获取所有已扫描的项目的key
        String keysString = "";
        for(int i=0;i<projectsIdName.length;i++){
            for(int j=0;j<componentsKeys.size();j++){
                if(projectsIdName[i].equals(componentsKeys.get(j).getKey())){
                    keysString += projectsIdName[i]+",";
                }
            }
        }

        String projectKeys = "";
        if(keysString.length() != 0){
            projectKeys = keysString.substring(0,keysString.length()-1);
        }
        return projectKeys;
    }

    public Boolean hasScaned(String projectKey,List<SonarComponentKeyVO> componentsKeys){
        for(int i=0; i<componentsKeys.size();i++){
            if(projectKey.equals(componentsKeys.get(i).getKey())){
                return true;
            }
        }

        return false;
    }

    public static void main(String[] args) throws IOException {
        SonarTest sonarTest = new SonarTest();
        //检查某个项目是否被扫描
        String componentString = sonarTest.getSonarResult(allProjectsPath);
        //json字符串转java对象
        System.err.println(componentString);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        SonarSearchProjectVO searchProjects = objectMapper.readValue(componentString, SonarSearchProjectVO.class);
        List<SonarComponentKeyVO> componentsKeys = searchProjects.getComponents();
        String projectKey = "KBG:KBG";
        Boolean hasScaned = sonarTest.hasScaned(projectKey,componentsKeys);
        System.err.println(projectKey + "是否被扫描【true被扫描/false没有被扫描】 : " + hasScaned);
        //获取某个项目扫描结果
        //metricKeys可选的值ncloc,complexity,violations
        String path = "/api/measures/component?additionalFields=metrics&componentKey="+projectKey+"&metricKeys=ncloc";
        String sonarResult = sonarTest.getSonarResult(path);
        System.err.println(projectKey+"的扫描结果是："+sonarResult);
        //获取某个项目组下已扫描项目的结果
        path = "/api/measures/search_history?component="+projectKey+"&metrics=ncloc";
        System.err.println(projectKey+"获取某个项目组下已扫描项目的结果:"+sonarTest.getSonarResult(path));

    }

}
